package repeat3;

import repeat.UdpDatagramServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-10-11
 * Time: 9:07
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //创建一个数据报
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //根据请求计算响应
            String response = process(request);
            //响应返回客户端3
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s,%d] , request: %s , response: %s\n"
                    ,requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
        }
    }


    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpDatagramServer server = new UdpDatagramServer(9096);
        server.start();
    }
}
